#-*- coding: UTF-8 -*-
import redis
from redis.sentinel import Sentinel

'''
Redis Config
'''
G_REDIS_HOST = '81.70.199.153'
G_REDIS_PORT = 6379
G_REDIS_SENTINEL_PORT = 26379
G_REDIS_SENTINEL_PORT1 = 26380
G_REDIS_SENTINEL_PORT2 = 26381
G_REDIS_PASSWORD = ''
G_REDIS_DB = 0
G_REDIS_KEY_PREFIX = 'cx:'
G_REDIS_SENTINEL = [('81.70.199.153', G_REDIS_SENTINEL_PORT), ('81.70.199.153', G_REDIS_SENTINEL_PORT1),
                    ('81.70.199.153', G_REDIS_SENTINEL_PORT2)]

G_REDIS_SENTINEL_PWD = ''
G_REDIS_TIMEOUT = 0.5




class RedisClietSentinel():

    def getMasterIpPort(self):
        try:
            sentinel = Sentinel(G_REDIS_SENTINEL, socket_timeout=G_REDIS_TIMEOUT)
            master = sentinel.discover_master('mymaster')
            return master
        except Exception as  e:
            print(e)

            return None

    def getSlavesIpPort(self):
        try:
            sentinel = Sentinel(G_REDIS_SENTINEL, socket_timeout=G_REDIS_TIMEOUT)
            slaves = sentinel.discover_slaves('mymaster')
            return slaves
        except Exception as  e:

            return None

    def getWriteRedis(self):
        try:
            sentinel = Sentinel(G_REDIS_SENTINEL, socket_timeout=G_REDIS_TIMEOUT)
            master = sentinel.master_for('mymaster', socket_timeout=G_REDIS_TIMEOUT,
                                         password=G_REDIS_SENTINEL_PWD, db=G_REDIS_DB)
            return master
        except Exception as  e:

            return None

    def getReadRedis(self):
        try:
            sentinel = Sentinel(G_REDIS_SENTINEL, socket_timeout=0.5)
            slave = sentinel.slave_for('mymaster', socket_timeout=0.5, password=G_REDIS_SENTINEL_PWD, db=G_REDIS_DB)
            return slave
        except Exception as  e:

            return None



if __name__ == '__main__':
    print(RedisClietSentinel().getMasterIpPort())
    print(RedisClietSentinel().getSlavesIpPort())
    print(RedisClietSentinel().getWriteRedis().set('d',2))
    print(RedisClietSentinel().getReadRedis().get('d'))





